/*
 * inicio.java
 *
 * Created on 2 de febrero de 2006, 04:51 PM
 */

package administrador;
import java.sql.*;
import javax.swing.*;

/**
 *
 * @author  Cesar Tenesaca Landi
 */
public class inicio extends javax.swing.JFrame {
    AdministradorApp app;
    Conexion conexion=new Conexion();  
    /**
     * Creates new form inicio 
     */
    public inicio(Administrador a) {
        initComponents();
        
        
    }
    public inicio(AdministradorApp app/*AdministradorView aview*/) {
        
        initComponents();
        this.app=app;
        trataConexion();
        
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        txt_usuario = new javax.swing.JTextField();
        txt_contrasena = new javax.swing.JPasswordField();
        cb_1 = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        b_conectar = new javax.swing.JButton();
        b_salir = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        txt_server = new javax.swing.JTextField();
        txt_puerto = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        bt_pre = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Conexion");
        getContentPane().setLayout(null);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Conectar al Sistema"));
        jPanel1.setLayout(null);

        jLabel1.setText("Usuario:");
        jPanel1.add(jLabel1);
        jLabel1.setBounds(90, 40, 60, 20);

        jLabel2.setText("Password:");
        jPanel1.add(jLabel2);
        jLabel2.setBounds(80, 70, 60, 20);

        txt_usuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txt_usuarioActionPerformed(evt);
            }
        });
        txt_usuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txt_usuarioKeyTyped(evt);
            }
        });
        jPanel1.add(txt_usuario);
        txt_usuario.setBounds(130, 40, 220, 20);

        txt_contrasena.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txt_contrasenaFocusLost(evt);
            }
        });
        txt_contrasena.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txt_contrasenaKeyTyped(evt);
            }
        });
        jPanel1.add(txt_contrasena);
        txt_contrasena.setBounds(130, 70, 220, 20);

        cb_1.setBackground(new java.awt.Color(240, 240, 240));
        cb_1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cb_1MouseClicked(evt);
            }
        });
        cb_1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cb_1ActionPerformed(evt);
            }
        });
        cb_1.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                cb_1FocusGained(evt);
            }
        });
        jPanel1.add(cb_1);
        cb_1.setBounds(130, 100, 220, 30);

        jLabel3.setText("  Sucursal:");
        jPanel1.add(jLabel3);
        jLabel3.setBounds(80, 100, 70, 20);

        b_conectar.setText("Conectar");
        b_conectar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                b_conectarActionPerformed(evt);
            }
        });
        jPanel1.add(b_conectar);
        b_conectar.setBounds(150, 140, 90, 23);

        b_salir.setText("Salir");
        b_salir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                b_salirActionPerformed(evt);
            }
        });
        jPanel1.add(b_salir);
        b_salir.setBounds(250, 140, 100, 23);

        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/administrador/resources/imagenes/password.png"))); // NOI18N
        jPanel1.add(jLabel5);
        jLabel5.setBounds(0, 10, 110, 150);

        jTabbedPane1.addTab("Conexion", jPanel1);

        jPanel2.setLayout(new java.awt.BorderLayout());

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Parametros"));
        jPanel3.setLayout(null);

        txt_server.setText("localhost");
        txt_server.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txt_serverActionPerformed(evt);
            }
        });
        jPanel3.add(txt_server);
        txt_server.setBounds(130, 80, 120, 20);

        txt_puerto.setText("3306");
        jPanel3.add(txt_puerto);
        txt_puerto.setBounds(130, 50, 120, 20);

        jLabel6.setText("  Servidor Host:");
        jPanel3.add(jLabel6);
        jLabel6.setBounds(40, 80, 80, 20);

        jLabel4.setText("Puerto Conexion:");
        jPanel3.add(jLabel4);
        jLabel4.setBounds(30, 50, 110, 20);

        bt_pre.setText("Predeterminado");
        bt_pre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_preActionPerformed(evt);
            }
        });
        jPanel3.add(bt_pre);
        bt_pre.setBounds(140, 110, 110, 23);

        jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/administrador/resources/imagenes/engine.png"))); // NOI18N
        jPanel3.add(jLabel7);
        jLabel7.setBounds(170, 10, 213, 170);

        jPanel2.add(jPanel3, java.awt.BorderLayout.CENTER);

        jTabbedPane1.addTab("Parametros", jPanel2);

        getContentPane().add(jTabbedPane1);
        jTabbedPane1.setBounds(10, 10, 370, 210);

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-427)/2, (screenSize.height-291)/2, 427, 291);
    }// </editor-fold>//GEN-END:initComponents

    private void txt_contrasenaKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_contrasenaKeyTyped
// TODO add your handling code here:
     int presiona=evt.getKeyChar();     
      if(presiona==10){
      establescoConexionBD();
      obtenerBodegas();
     }
    }//GEN-LAST:event_txt_contrasenaKeyTyped
    public void trataConexion(){
    
    
    };
    
    public void conectarAdmin(){
      //Tomar la Bodega:
      int bodega=tomoBodega();
      
      String puerto=txt_puerto.getText();
      String server=txt_server.getText();
      
      String nombreU=txt_usuario.getText();
      String contrasenaU=txt_contrasena.getText();
              
      //Saco el Usuario:close
      ResultSet r=conexion.consultarBase("select * from usuario where login like '"+nombreU+"' and clave like PASSWORD('"+contrasenaU+"')");
      int num=0;
      num=conexion.obtenerFilas(r);
      
      System.out.println("El numero de filas es:"+num);
      if(num==0){
            JOptionPane.showMessageDialog(this, "El usuario o clave son Incorrectos", "Informacion", JOptionPane.INFORMATION_MESSAGE);
        } else {

            Usuario user = null;
            try {
                user = new Usuario(r.getString(4), r.getString(2), r.getString(3));

            } catch (SQLException ex) {
                ex.printStackTrace();
            }

            //Muestro del Viewer desde la Aplicacion:
            AdministradorView aview = new AdministradorView(app);
            app.show(aview);
            
            //Defino los datos de control:
            aview.bodega = bodega;
            aview.c = conexion;
            aview.user = user;
            
            //Defino los paneles y opciones de Usuario:
            aview.refrescar();
            
            //Pongo la  ventana de Presentacion:
            aview.caracteristicas();
            
            //En el caso que sea un Administrador Inicio el Timer:
//            if(user.getPrivilegio().equals("m")){
//            //Inicio el Timer
//            Timer tempo=new Timer("Tempo1",aview,conexion);
//            Thread hilo = new Thread(tempo);
//            hilo.start();//Inicio el Timer
//            //Pongo el Timer en el Viewer
//            aview.setTimer(tempo);
//
//            }

             //Inicio el Actualizador de Internet:
            HiloActualiza ha=new HiloActualiza(conexion,bodega);
            ha.start();
            
            this.dispose();
        }
          
     
    }
    
    public void establescoConexionBD() {
        if(conexion.estado==false)
        {
            //Establece la conexion:
            String nombreU = txt_usuario.getText();
            String contrasenaU = txt_contrasena.getText();
            String puerto=this.txt_puerto.getText();
            String server=this.txt_server.getText();
            conexion = new Conexion();
            conexion.conectarBase(nombreU, contrasenaU,puerto,server);

        //********************
        }
    }
    
    public void obtenerBodegas(){
        cb_1.removeAllItems();
        //Obtengo numeo de Bodegas de la Base de Datos:
       
        ResultSet r;
        
        try{
            try{
               
                r=conexion.consultarBase("select * from Bodega");
                r.beforeFirst();
                while(r.next()){
                int codBodega=r.getInt(1);
                String nomBodega=r.getString(2);
                //System.out.println(codBodega+" "+nomBodega);
                cb_1.addItem(codBodega+" | "+nomBodega);
                }        
                
            }catch(SQLException sqle){
                System.out.println("Error al mostrar los resultados de la consulta");
                System.err.println(sqle);}
        }catch(Exception e){System.out.println("Error de una Excepcion.");}
        
            
    }
    private void cb_1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cb_1ActionPerformed
// TODO add your handling code here:      
       
    }//GEN-LAST:event_cb_1ActionPerformed

    private void b_salirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_salirActionPerformed
           System.exit(0);
    }//GEN-LAST:event_b_salirActionPerformed
    public int tomoBodega(){
    int i=0;
    i=Integer.valueOf(cb_1.getSelectedItem().toString().split(" ")[0]);
    //System.out.println("La bodega que toma es:"+i);
    return i; 
    }
    private void b_conectarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_b_conectarActionPerformed
     conectarAdmin();
    }//GEN-LAST:event_b_conectarActionPerformed

private void txt_usuarioKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_usuarioKeyTyped
// TODO add your handling code here:
}//GEN-LAST:event_txt_usuarioKeyTyped

private void cb_1FocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_cb_1FocusGained
// TODO add your handling code here:
    if(conexion.estado==true){
    obtenerBodegas();
    }
    
}//GEN-LAST:event_cb_1FocusGained

private void bt_preActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_preActionPerformed
// TODO add your handling code here:
    txt_puerto.setText("3306");
    txt_server.setText("localhost");
}//GEN-LAST:event_bt_preActionPerformed

private void txt_contrasenaFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txt_contrasenaFocusLost
// TODO add your handling code here:
    
}//GEN-LAST:event_txt_contrasenaFocusLost

private void cb_1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cb_1MouseClicked
// TODO add your handling code here:
    establescoConexionBD();
       obtenerBodegas();
}//GEN-LAST:event_cb_1MouseClicked

private void txt_serverActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_serverActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_serverActionPerformed

private void txt_usuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txt_usuarioActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_txt_usuarioActionPerformed
  
    
    

    /**
     * @param args the command line arguments
     */

    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton b_conectar;
    private javax.swing.JButton b_salir;
    private javax.swing.JButton bt_pre;
    private javax.swing.JComboBox cb_1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JPasswordField txt_contrasena;
    private javax.swing.JTextField txt_puerto;
    private javax.swing.JTextField txt_server;
    private javax.swing.JTextField txt_usuario;
    // End of variables declaration//GEN-END:variables
    
}
